<template>
  <div class="thirder_div">
    <div class="person_tab_div">
      <div v-if="thirdPersonMap != null && Object.keys(thirdPersonMap).length != 0" class="">
        <div class="tag_div" style="margin: 10px 0px">
          <span style="font-weight: bold;">第三人：</span>
          <div v-for="(item, key, index) in thirdPersonMap" :key="index" class="tag_div">
            <div v-for="(thirder, personKey) in thirdPersonMap[key]" :key="personKey">
              <a-tag color="#0072c6" :class="thirderKey == thirder.id ? 'tag_content_select_div' : 'tag_content_noselect_div'" @click="editThirderPerson(thirder, key)"> {{ thirder.name }}</a-tag>
            </div>
          </div>
        </div>
        <ThirdPersonAddView ref="thirdPersonAddRef" :applyid="applyid" @requery="getThirdPerson"></ThirdPersonAddView>
      </div>
      <a-empty v-else style="min-height: 300px" />
    </div>

    <!-- <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic> -->
  </div>
</template>
<script>
import { saveMaterialRepeat } from '@/api/accept/aprv_process_materials'
import { getThirdWithGroup, updateAttachId, deleteAttachId } from '@/api/accept/apl_thirdper'
import { Tp_applicantList, Tp_applicantValue } from '@/enumeration/Tp_applicant'
import { Tp_cardList } from '@/enumeration/Tp_card'
import { minioUploadMore } from '@/api/base/file'
import { kkfilePreview } from '@/utils/util.js'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'
import { Tp_proctypeValue } from  '@/enumeration/Tp_proctype'
import { APP_USER } from '@/store/mutation-types.js'
import storage from 'store'
import { downloadFileWithUrl } from '@/utils/util'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    },
    isEditModel: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data () {
    return {
      loading: false, // 遮罩是否显示
      Tp_applicant: Tp_applicantList,
      Tp_applicantValue: Tp_applicantValue,
      Tp_card: Tp_cardList,
      currentUser: storage.get(APP_USER), // 登录人信息
      Tp_procmaterialValue: Tp_procmaterialValue,
      Tp_proctypeValue: Tp_proctypeValue,
      columns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '第三人类型',
          width: '150px',
          key: 'type',
          dataIndex: 'type',
          scopedSlots: { customRender: 'typeSlot' }
        },
        {
          title: '名称',
          width: '150px',
          key: 'name',
          dataIndex: 'name',
          scopedSlots: { customRender: 'nameSlot' }
        },
        {
          title: '证件类型',
          key: 'cardtype',
          dataIndex: 'cardtype',
          width: '120px',
          scopedSlots: { customRender: 'cardtypeSlot' }
        },
        {
          title: '证件号',
          key: 'cardno',
          dataIndex: 'cardno',
          width: '150px',
          scopedSlots: { customRender: 'cardnoSlot' }
        },
        {
          title: '联系号码',
          key: 'tel',
          dataIndex: 'tel',
          width: '150px'
        },
        {
          title: '联系地址',
          key: 'addr',
          dataIndex: 'addr',
          width: '250px',
          scopedSlots: { customRender: 'addrSlot' }
        },
        {
          title: '身份证明',
          dataIndex: 'filecardList',
          key: 'filecardList',
          width: '250px',
          scopedSlots: { customRender: 'filecardSlot' }
        },
        {
          title: '第三人材料证明',
          dataIndex: 'thirdEvidenceList',
          key: 'thirdEvidenceList',
          width: '250px',
          scopedSlots: { customRender: 'thirdEvidenceSlot' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      unitColumns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '第三人类型',
          width: '150px',
          key: 'type',
          dataIndex: 'type',
          scopedSlots: { customRender: 'typeSlot' }
        },
        {
          title: '名称',
          width: '150px',
          key: 'name',
          dataIndex: 'name'
        },
        {
          title: '证件号',
          key: 'cardno',
          dataIndex: 'cardno',
          width: '150px'
        },
        {
          title: '联系号码',
          key: 'tel',
          dataIndex: 'tel',
          width: '120px'
        },
        {
          title: '法定代表人',
          key: 'manager',
          dataIndex: 'manager',
          width: '150px'
        },
        {
          title: '职务',
          key: 'job',
          dataIndex: 'job',
          width: '150px'
        },
        {
          title: '身份证明书',
          dataIndex: 'doccardList',
          key: 'doccardList',
          width: '250px',
          scopedSlots: { customRender: 'doccardSlot' }
        },
        {
          title: '第三人材料证明',
          dataIndex: 'thirdEvidenceList',
          key: 'thirdEvidenceList',
          width: '250px',
          scopedSlots: { customRender: 'thirdEvidenceSlot' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      thirdPersonMap: {}, // 第三人数据
      selectData: {}, // 点击按钮选择的行数据
      operateType: undefined, // 操作类型 0：身份证明 1:身份证明书，2：第三人证明材料
      btnShow: true, //  按钮展示
      activeKey: [],
      acceptFileType: FILETYPE,
      thirderKey: undefined,
    }
  },
  components: {
    ThirdPersonAddView: () => import('@/views/accept/material/ThirdPersonAddView.vue'),
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  created () {
    if (this.isEditModel) {
      this.btnShow = true
    } else {
      this.btnShow = false
    }
    // FIXME: 临时放开
    this.btnShow = true
  },
  async mounted () {
    this.$nextTick(async () => {
      this.thirderKey = undefined
      await this.getThirdPerson()
    })
  },
  methods: {
    async getThirdPerson () {
      let res = await getThirdWithGroup({ applyid: this.applyid })
      if (res.code == 0) {
        this.thirdPersonMap = res.data
        if (this.thirdPersonMap != null && this.thirdPersonMap != undefined && Object.keys(this.thirdPersonMap).length >= 0) {
          if (!this.thirderKey) {
            for (const key in this.thirdPersonMap) {
              const numberKey = Number(key)
              if (this.thirdPersonMap[numberKey]) {
                if (this.thirdPersonMap[numberKey][0] && !this.applicantKey) {
                  this.thirderKey = this.thirdPersonMap[numberKey][0].id
                  this.initThirderPerson(this.thirdPersonMap[numberKey][0], numberKey)
                }
              }
            }
          } else {
            for (const key in this.thirdPersonMap) {
              const numberKey = Number(key)
              if (this.thirdPersonMap[numberKey]) {
                for (let index = 0; index < this.thirdPersonMap[numberKey].length; index++) {
                  if (this.thirderKey == this.thirdPersonMap[numberKey][index].id) {
                    this.initThirderPerson(this.thirdPersonMap[numberKey][index], numberKey)
                  }
                }
              }
            }
          }
        }
      } else {
        this.thirdPersonMap = {}
      }
    },
    initThirderPerson (record) {
      this.thirderKey = record.id
      setTimeout(() => {
        if (this.$refs.thirdPersonAddRef) {
          this.$refs.thirdPersonAddRef.init(true, record)
        }
      }, 100)
    },
    editThirderPerson (record) {
      this.thirderKey = record.id
      this.$nextTick(() => {
        if (this.$refs.thirdPersonAddRef) {
          this.$refs.thirdPersonAddRef.init(true, record)
        }
      })
    },
    downloadFile (file) {
      const x = new XMLHttpRequest()
      x.open('GET', file.path, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = file.filename
        a.click()
      }
      x.send()
    },
    downloadFiles (record, type) {
      let fileList = []
      if (type == 1) {
        if (record.filecardList && record.filecardList.length > 0) {
          fileList = record.filecardList
        }
      } else if (type == 2) {
        if (record.doccardList && record.doccardList.length > 0) {
          fileList = record.doccardList
        }
      }
      if (record.thirdEvidenceList && record.thirdEvidenceList.length > 0) {
        fileList = fileList.concat(record.thirdEvidenceList)
      }
      for (const index in fileList) {
        const file = fileList[index]
        const x = new XMLHttpRequest()
        x.open('GET', file.path, true)
        x.responseType = 'blob'
        x.onload = function (e) {
          const url = window.URL.createObjectURL(x.response)
          const a = document.createElement('a')
          a.href = url
          a.download = file.filename
          a.click()
        }
        x.send()
      }
    },
    // 状态转换显示
    typeLable (val) {
      for (const key in this.Tp_applicant) {
        if (this.Tp_applicant[key].value == val) {
          return this.Tp_applicant[key].name
        }
      }
      return val
    },
    cardTypeLable (val) {
      for (const key in this.Tp_card) {
        if (this.Tp_card[key].value == val) {
          return this.Tp_card[key].name
        }
      }
      return val
    },
    // 上传附件
    uploadFile (record, operateType) {
      this.selectData = record
      this.operateType = operateType
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
     importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      if (this.operateType == null || this.operateType == undefined) {
        this.$message.error('操作类型为空')
      }
      if (this.operateType == 0 || this.operateType == 1) {
        minioUploadMore(files).then((res) => {
          if (res.code == 0) {
            let attachs = res.data
            let attachids = []
            attachs.forEach((item) => {
              attachids.push(item.id)
            })
            if (this.selectData.attachid != '' && this.selectData.attachid != null) {
              const selectAttachIds = this.selectData.attachid.split(',')
              attachids = attachids.concat(selectAttachIds)
            }
            if (this.operateType == 0) {
              // 身份证明
              if (this.selectData.filecard != '' && this.selectData.filecard != null) {
                const filecardIds = this.selectData.filecard.split(',')
                attachids = attachids.concat(filecardIds)
              }
            } else if (this.operateType == 1) {
              // 身份证明书
              if (this.selectData.doccard != '' && this.selectData.doccard != null) {
                const doccardIds = this.selectData.doccard.split(',')
                attachids = attachids.concat(doccardIds)
              }
            } else if (this.operateType == 2) {
              // 第三人证据材料
              if (this.selectData.thirdevidence != '' && this.selectData.thirdevidence != null) {
                const thirdEvidenceIds = this.selectData.thirdevidence.split(',')
                attachids = attachids.concat(thirdEvidenceIds)
              }
            }
            updateAttachId({ id: this.selectData.id, type: this.operateType, attachid: attachids.join(',') }).then((res2) => {
              if (res2.code == 0) {
                this.getThirdPerson()
                this.$message.success('上传成功')
                this.$refs.multiUploadBasic.handleCancel()
              } else {
                this.$message.error('上传失败')
                this.$refs.multiUploadBasic.handleCancel()
              }
            })
          }
        }).finally(() => {
          this.$refs.multiUploadBasic.loading = false
        })
      } else if (this.operateType == 2) {
        const param = {
          applyid: this.applyid,
          fileType: this.Tp_procmaterialValue.MATER_INVENTORY,
          busiType: this.Tp_proctypeValue.ACCEPT_ACCEPT,
          userId: this.currentUser.userId,
          userName: this.currentUser.fullname
        }
        saveMaterialRepeat(param, importFileList)
          .then(res => {
            if (res.code !== 0) {
              this.$message.error(res.msg)
            } else {
                let attachs = res.data
                let attachids = []
                attachs.forEach((item) => {
                  attachids.push(item.attachid)
                })
                  // 第三人证据材料
                if (this.selectData.thirdevidence != '' && this.selectData.thirdevidence != null) {
                  const thirdEvidenceIds = this.selectData.thirdevidence.split(',')
                  attachids = attachids.concat(thirdEvidenceIds)
                }
                updateAttachId({ id: this.selectData.id, type: this.operateType, attachid: attachids.join(',') }).then((res2) => {
                  if (res2.code == 0) {
                    this.getThirdPerson()
                    this.$message.success('上传成功')
                    this.$refs.multiUploadBasic.handleCancel()
                  } else {
                    this.$message.error('上传失败')
                    this.$refs.multiUploadBasic.handleCancel()
                  }
                })
            }
          })
          .catch(err => {
            console.log(err, '上传数据失败')
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    // 删除文件，涉及到接口的调用
    deleteFile (record, file, type) {
      if (type == null || type == undefined) {
        this.$message.error('操作类型为空')
      }
      deleteAttachId({ id: record.id, type: type, attachid: file.id }).then((res) => {
        console.log('deleteAttachId', res.data)
        if (res.code == 0) {
          this.getThirdPerson()
        } else {
          this.$message.success('删除失败')
        }
      })
    },
    // 新增第三人
    addNewThird () {
      this.$refs.thirdPersonAddRef.init(false)
    },
    // 预览文件
    previewFile (record) {
      window.open(kkfilePreview(record.path))
    }
  }
}
</script>
<style lang="less" scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.add_btn {
  z-index: 20;
  margin-left: 90%;
}

.file-css {
  display: block;
  margin-bottom: 5px;
  word-break: break-all;
}

.hover-delete {
  display: none;
  color: red;
}

.hover-div:hover .hover-delete {
  display: inline-block;
  padding-left: 10px;
  color: red;
}

// /deep/ .ant-table-tbody > tr > td {
//   border: 0;
// }

// /deep/.ant-table-thead > tr > th {
//   font-size: 16px !important;
//   color: #666666 !important;
//   border: 0;
// }
.link_css {
  display: block;
}

.thirder_div {
  background-color: #fff;
  padding: 16px;
}

.tag_div {
  display: flex;
  align-items: center;
  flex-direction: row;
  font-size: 16px;
}
.tag_content_select_div {
  background-color: rgb(0, 114, 198);
  font-size: 16px;
  min-width: 100px;
  height: 32px;
  line-height: 30px;
  text-align: center;
  border-radius: 0px;
}
.tag_content_noselect_div {
  background-color: #f3f6fb !important;
  font-size: 16px;
  height: 32px;
  min-width: 100px;
  line-height: 24px;
  text-align: center;
  border-radius: 0px;
  color: black;
}
.person_matrial_label {
  display: flex;
  font-size: 16px;
  margin: 0px 10px;
}
</style>
